package com.itheima.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

@Configuration//声明此类是Spring配置类
@ComponentScan("com.itheima")//开启包扫描
@PropertySource("classpath:jdbc.properties")//加载properties配置文件
@EnableAspectJAutoProxy//开启AOP注解支持
@EnableTransactionManagement//开启事务注解支持
public class SpringConfig {
    @Value("${jdbc.driver}")
   private String driver;
    @Value("${jdbc.url}")
   private String url;
    @Value("${jdbc.username}")
   private String username;
    @Value("${jdbc.password}")
   private String password;

    @Bean
    public JdbcTemplate getJdbcTemplate(@Qualifier("dataSource")DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
    @Bean("dataSource")
    public DataSource getDataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(driver);
        dataSource.setJdbcUrl(url);
        dataSource.setUser(username);
        dataSource.setPassword(password);
        return dataSource;
    }
    @Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(@Qualifier("dataSource")DataSource dataSource){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;

    }
}
